-module(kvs).
-compile(export_all).

start() ->
    register(kvs, spawn(fun() -> loop(kvs, dict:new()) end)).

store(Key, Value) -> rpc({store, Key, Value}).

lookup(Key) -> rpc({lookup, Key}).

rpc(Q) ->
    kvs ! {self(), Q},
    receive
        {kvs, Reply} ->
            Reply
    end.

loop(Name, Dict) ->
    receive
        {_From, store, Key, Value} ->
            Dict1 = dict:store(Key, Value, Dict),
            loop(Name, Dict1);
        {From, lookup, Key} ->
            case dict:find(Key, Dict) of
                {ok, Value} ->
                    From ! {Name, {ok, Value}};
                error ->
                    From ! {Name, undefined}
            end,
            loop(Name, Dict)
    end.
    
